// transfers.js (新建文件，放在根目录下)
// 模拟用户信息 (实际应用中应从登录状态获取)
const userInfo = {
  name: '糕辰鲤雪缪' // 从profile.html获取的用户名
};

// 确认转账
function confirmTransfer() {
  const receiver = document.getElementById('receiver').value;
  // 将 'transfers-amount' 修改为 'transfer-amount'，与HTML中的ID保持一致
  const amount = parseFloat(document.getElementById('transfer-amount').value);
  const remark = document.getElementById('remark').value || '转账';
  
  if (!receiver || isNaN(amount) || amount < 0.01) {
    alert('请填写正确信息');
    return;
  }
  
  if (confirm(`向 ${receiver} 转账 ${amount} 元\n备注：${remark}`)) {
    // 保存到数据库
    saveTransferToDatabase(userInfo.name, receiver, amount, remark)
      .then(() => {
        // 模拟扣除余额 (实际应用中应与账户系统集成)
        alert('转账成功！');
        window.history.back();
      })
      .catch(error => {
        console.error('转账失败:', error);
        alert('转账失败，请稍后再试');
      });
  }
}

// 保存转账记录到数据库
function saveTransferToDatabase(sender, receiver, amount, remark) {
  return fetch('/api/transfers', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      sender: sender,
      receiver: receiver,
      amount: amount,
      remark: remark
    })
  })
  .then(response => response.json())
  .then(data => {
    if (!data.success) {
      throw new Error(data.message || '保存转账记录失败');
    }
    return data;
  });
}

// 获取转账记录
function fetchTransfers() {
  fetch('/api/transfers')  // 已修正为相对路径
    .then(response => response.json())
    .then(data => {
      if (data.success && data.transfers.length > 0) {
        document.querySelector('.empty-state').style.display = 'none';
        renderTransfers(data.transfers);
      } else {
        document.querySelector('.empty-state').style.display = 'block';
      }
    })
    .catch(error => {
      console.error('获取转账记录失败:', error);
      alert('获取转账记录失败，请稍后再试');
    });
}

// 渲染转账记录
function renderTransfers(transfers) {
  const transfersList = document.getElementById('transfers-list');
  transfersList.innerHTML = '';
  
  transfers.forEach(transfer => {
    const item = document.createElement('div');
    item.className = 'history-item';
    item.innerHTML = `
      <div class="history-content">
        <h4>向 ${transfer.receiver} 转账</h4>
        <p>${transfer.timestamp}</p>
        <p class="transfer-remark">备注: ${transfer.remark || '无'}</p>
      </div>
      <div class="history-amount">-${transfer.amount}元</div>
    `;
    transfersList.appendChild(item);
  });
}